﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using Castle.Core.Logging;
using ComponentFactory.Krypton.Toolkit;

namespace TVN.ShopMan.ApplicationInterface.AppForms
{
    using TVN.Common.Helpers;
    using TVN.Common.Interfaces;
    using TVN.ShopMan.ActiveModels;
    using TVN.ShopMan.ApplicationInterface.Helpers;

    public partial class ProductImportForm : Form
    {
        /// <summary>
        /// All columns in the grid
        /// </summary>
        private class ColumnIndex
        {
            public const int Id = 0;
            public const int Name = 1;
            public const int Cost = 2;
            public const int Price = 3;
        }

        private static readonly ILogger _logger = Program.Logger.CreateChildLogger("ProductImportForm");
        private IRepository<Product> productRepository = null;
        private List<Product> listOfProducts = new List<Product>();
        private List<Product> listOfRemovedProducts = new List<Product>();
        private List<Product> listOfSelectedProducts = new List<Product>();
        private Repository selectedRepository = null;

        #region Constructors

        public ProductImportForm()
        {
            InitializeComponent();

            this.SetUp();
        }

        #endregion

        #region Private methods

        /// <summary>
        /// Setup the data grid
        /// </summary>
        private void SetUp()
        {
            this.productRepository = Program.Container.Resolve<IRepository<Product>>();
        }

        /// <summary>
        /// Displays current selected repository to the form. If user has not selected a repo yet, we display a warning message.
        /// </summary>
        private void DisplaySelectedRepository()
        {
            if (this.selectedRepository == null)
            {
                this.lblRepositoryInfo.Text = "You have not select a repository yet.";
            }
            else
            {
                this.lblRepositoryInfo.Text = string.Format("The selected repository: {0}.", this.selectedRepository.Name);
            }
        }

        /// <summary>
        /// Setup the grid of products include its columns.
        /// </summary>
        private void SetupProductsGrid()
        {
            this.kdgvProducts.AutoGenerateColumns = false;
            var idColumn = new DataGridViewColumn
            {
                DataPropertyName = Product.Properties.Id,
                Name = Product.Properties.Id,
                HeaderText = "Id",
                ValueType = typeof(int),
                CellTemplate = new DataGridViewTextBoxCell(),
                Visible = false
            };
            this.kdgvProducts.Columns.Add(idColumn);

            var nameColumn = new DataGridViewColumn
            {
                DataPropertyName = Product.Properties.Name,
                Name = Product.Properties.Name,
                HeaderText = "Name",
                ValueType = typeof(string),
                CellTemplate = new DataGridViewTextBoxCell(),
                Visible = true,
                MinimumWidth = 200,
            };
            this.kdgvProducts.Columns.Add(nameColumn);

            var costColumn = new DataGridViewColumn
            {
                DataPropertyName = Product.Properties.Cost,
                Name = Product.Properties.Cost,
                HeaderText = "Cost",
                ValueType = typeof(decimal),
                CellTemplate = new DataGridViewTextBoxCell(),
                Visible = true
            };
            this.kdgvProducts.Columns.Add(costColumn);

            var priceColumn = new DataGridViewColumn
            {
                DataPropertyName = Product.Properties.Price,
                Name = Product.Properties.Price,
                HeaderText = "Price",
                ValueType = typeof(decimal),
                CellTemplate = new DataGridViewTextBoxCell(),
                Visible = true
            };
            this.kdgvProducts.Columns.Add(priceColumn);
        }

        private void DisplayProductData(IList<Product> listOfProducts)
        {
            if ((listOfProducts != null) && (listOfProducts.Count > 0))
            {
                List<DataGridViewRow> rowsToRemove = new List<DataGridViewRow>();
                foreach (DataGridViewRow rowItem in this.kdgvProducts.Rows)
                {
                    Product localProduct = listOfProducts.FirstOrDefault(productItem => productItem.Id.Equals(rowItem.Cells[ColumnIndex.Id].Value));
                    if (localProduct == default(Product))
                    {
                        rowsToRemove.Add(rowItem);
                    }
                    else
                    {

                    }
                }

                foreach (Product productItem in listOfProducts)
                {

                }
            }
            else
            {
                this.kdgvProducts.Rows.Clear();
            }
        }

        private DialogResult ConfirmRemoveProducts()
        {
            var result = DialogResult.None;

            if (this.kdgvProducts.SelectedRows.Count > 0)
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("Are you sure you want to delete these product:");
                sb.AppendLine();
                foreach (DataGridViewRow rowItem in this.kdgvProducts.SelectedRows)
                {
                    sb.AppendFormat("   {0}", rowItem.Cells[ColumnIndex.Name].Value);
                    sb.AppendLine();
                }

                result = KryptonMessageBox.Show(sb.ToString(), "Delete?", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
            }

            return result;
        }

        /// <summary>
        /// Detects has changes on products or not.
        /// </summary>
        /// <returns></returns>
        private bool HasChanged()
        {
            bool result = false;
            if ((this.listOfRemovedProducts != null) && (this.listOfRemovedProducts.Count() > 0))
            {
                result = true;
            }
            else if (this.listOfProducts != null)
            {
                if (this.listOfProducts.FirstOrDefault(productItem => (productItem.Id < 0)) != null)
                {
                    result = true;
                }
                else
                {
                }
            }

            return result;
        }

        private void SaveChanges()
        {
            if (this.listOfRemovedProducts != null)
            {
                foreach (Product productItem in this.listOfRemovedProducts)
                {
                    if (productItem != null)
                    {
                        productItem.Delete();
                    }
                }
            }

            if (this.listOfProducts != null)
            {
                foreach (Product productItem in this.listOfProducts)
                {
                    productItem.Save();
                }
            }
        }

        #endregion

        #region Events

        private void btnAddProducts_Click(object sender, EventArgs e)
        {
            using (ProductSelectionForm productsForm = new ProductSelectionForm(this.listOfSelectedProducts)
            {
                StartPosition = FormStartPosition.CenterParent
            })
            {
                var result = productsForm.ShowDialog();
                if (result == DialogResult.OK)
                {
                    this.listOfSelectedProducts.Clear();
                    productsForm.SelectedProducts.ForEach(delegate(Product productItem)
                    {
                        if (this.listOfSelectedProducts.Exists(delegate(Product selectedProduct)
                        {
                            return (selectedProduct.Id.Equals(productItem.Id));
                        }))
                        {
                            this.listOfSelectedProducts.Add(productItem);
                        }
                    });
                    this.listOfSelectedProducts = productsForm.SelectedProducts;
                }
            }
        }

        private void btnRemoveProducts_Click(object sender, EventArgs e)
        {

        }

        private void btnSelectRepository_Click(object sender, EventArgs e)
        {
            using (var repositoryForm = new RepositorySelectionForm(this.selectedRepository)
            {
                StartPosition = FormStartPosition.CenterParent
            })
            {
                var result = repositoryForm.ShowDialog();
                if (result == DialogResult.OK)
                {
                    this.selectedRepository = repositoryForm.SelectedRepository;
                    this.DisplaySelectedRepository();
                }
            }
        }

        private void btnSaveChanges_Click(object sender, EventArgs e)
        {
            try
            {
                this.SaveChanges();

                this.DialogResult = DialogResult.OK;
                this.Close();
                this.Dispose();

                GC.SuppressFinalize(this);
            }
            catch (Exception ex)
            {
                this.DialogResult = DialogResult.No;
                _logger.Error("Error while saving changes", ex);
            }
        }

        private void kdgvProducts_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            switch (e.ColumnIndex)
            {
                default:
                    break;
            }
        }

        private void kdgvProducts_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                DataGridViewCell modifiedCell = this.kdgvProducts.Rows[e.RowIndex].Cells[e.ColumnIndex];

                int productId = Convert.ToInt32(this.kdgvProducts.Rows[e.RowIndex].Cells[ColumnIndex.Id].Value);
                Product selectedProduct = this.listOfProducts.FirstOrDefault(item => (item.Id == productId));

                switch (e.ColumnIndex)
                {
                    case ColumnIndex.Name:
                        selectedProduct.Name = Convert.ToString(modifiedCell.Value);
                        break;
                }
            }
            catch (Exception ex)
            {
                _logger.ErrorFormat(ex, "Error while editing cell: {0}", e.ColumnIndex);
            }
        }

        private void kdgvProducts_UserDeletedRow(object sender, DataGridViewRowEventArgs e)
        {
            int productId = Convert.ToInt32(e.Row.Cells[ColumnIndex.Id].Value);
            Product productItem = this.listOfProducts.FirstOrDefault(item => (item.Id == productId));

            if (this.listOfRemovedProducts == null)
            {
                this.listOfRemovedProducts = new List<Product>();
            }
            this.listOfProducts.Remove(productItem);
        }

        private void kdgvProducts_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
        {
            if (this.ConfirmRemoveProducts() != DialogResult.Yes)
            {
                e.Cancel = true;
            }
        }

        private void ProductImportForm_Load(object sender, EventArgs e)
        {
            this.DisplaySelectedRepository();
            this.SetupProductsGrid();
        }

        private void ProductImportForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (this.HasChanged())
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("There is some changes on products. Do you want to save these changes?");

                DialogResult result = KryptonMessageBox.Show(sb.ToString(), "Confirmation", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
                switch (result)
                {
                    case DialogResult.Yes:
                        try
                        {
                            this.SaveChanges();

                            this.Close();
                            this.Dispose();

                            GC.SuppressFinalize(this);
                        }
                        catch (Exception ex)
                        {
                            this.DialogResult = DialogResult.No;
                            _logger.Error("Error while saving changes", ex);
                        }
                        break;

                    case DialogResult.Cancel:
                        e.Cancel = true;
                        break;
                }
            }
        }

        #endregion

    }
}